package com.chainyoung.component_tmperson.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chainyoung.common.appcommon.entity.UploadFile;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.imageloader.ImageLoader;
import com.chainyoung.common.imageloader.glide.GlideImageConfig;
import com.chainyoung.common.imageloader.glide.transformations.RoundedCornersTransformation;
import com.chainyoung.common.imageloader.glide.transformations.RoundedCornersTransformationNew;
import com.chainyoung.common.utils.AppUtils;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.ConvertUtils;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.utils.Utils;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.ui.mvp.contract.UpdateUserInfoContract;
import com.chainyoung.component_tmperson.ui.mvp.presenter.UpdateUserInfoPresenter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class EditUserInfoActivity extends BaseActivity<UpdateUserInfoPresenter> implements UpdateUserInfoContract.View {

    @BindView(R2.id.iv_logo)
    ImageView ivLogo;
    @BindView(R2.id.tv_name)
    EditText etName;


    private ImageLoader imageLoader;
    private List<String> selectImgs = new ArrayList<>();
    private String originName;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUI() {
        setCurrentTitle(getString(R.string.tmperson_edit_person_info));
        imageLoader = Utils.getAppComponent().imageLoader();
        UserInfo userInfo = CommonUtil.getUserInfo();
        originName = userInfo.getUsername();
        etName.setText(userInfo.getUsername());
        etName.setSelection(etName.getText().length());
        imageLoader.loadImage(mContext,
                GlideImageConfig
                        .builder()
                        .url(userInfo.getAvatar())
                        .imagerView(ivLogo)
                        .transformation(new RoundedCornersTransformationNew(15, 0))
                        .build());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_edit_user_info;
    }

    @OnClick(R2.id.tv_submit)
    public void onSubmit() {
        if (StringUtil.viewGetTextIsEmpty(etName)) {
            ToastUtil.showToast(getString(R.string.tmperson_pls_input_nick_name));
            return;
        }
        if (!StringUtil.isUserNameValidate(etName.getText().toString().trim())) {
            ToastUtil.showToast(getString(R.string.tmperson_pls_input_correct_name));
            return;
        }
        if (!selectImgs.isEmpty()) {
            mPresenter.updateUserLogo(selectImgs.get(0), 1);
        } else if (!StringUtil.viewGetText(etName).equals(originName)) {
            updateUserInfo(StringUtil.viewGetText(etName), null,false);
        } else {
            finish();
        }

    }

    private void updateUserInfo(String userName, String logo,boolean isAfterUpdateLogo) {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        if (!TextUtils.isEmpty(userName)) {
            map.put("username", userName);
        }
        if (!TextUtils.isEmpty(logo)) {
            map.put("avatar", logo);
        }
        mPresenter.updateUserInfo(map,isAfterUpdateLogo);
    }

    @OnClick(R2.id.rl_logo)
    void selectLogo() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .enableCrop(true)
                .scaleEnabled(true)
                .rotateEnabled(false)
                .withAspectRatio(1,1)
                .freeStyleCropEnabled(true)
                .glideOverride(160, 160)
                .compress(true)
                .compressSavePath(AppUtils.getImagePath())
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    selectImgs.clear();
                    for (LocalMedia media : selectList) {
                        selectImgs.add(media.getCompressPath());
                        Log.i("图片-----》", media.getCompressPath());
                    }
                    if (!selectImgs.isEmpty()) {
                        Glide.with(mContext).load(selectImgs.get(0)).apply(RequestOptions.placeholderOf(R.mipmap.ic_default).error(R.mipmap.ic_default)).into(ivLogo);
                    }
                    break;
            }
        }
    }

    @Override
    public void updataUserInfoSuccess(UserInfo data) {
        UserInfo userInfo = CommonUtil.getUserInfo();
        data.setIs_setpaypassword(userInfo.getIs_setpaypassword());
        data.setToken(userInfo.getToken());
        data.setH5_chat_url(userInfo.getH5_chat_url());
        CommonUtil.setUserInfo(data);
        finish();
    }

    @Override
    public void uploadImgSuccess(UploadFile data) {
        updateUserInfo(StringUtil.viewGetText(etName), data.getUrl(),true);
    }


}
